<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-button type="primary" @click="addDialogVisible = true"
        >添加角色</el-button
      >
      <!-- 表格区域 -->
      <el-table :data="rolesList" border stripe>
        <el-table-column type="expand">
          <template v-slot="scope">
            <!-- 权限标签渲染区域 -->
            <el-row
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
              :class="['bb', i1 === 0 ? 'bt' : '']"
            >
              <!-- 一级权限 五列 -->
              <el-col :span="5">
                <el-tag @close="deleteRights(scope.row, item1.id)" closable>{{
                  item1.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级，三级权限 十九列 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  :class="[i2 === 0 ? '' : 'bt']"
                >
                  <!-- 二级 -->
                  <el-col :span="6">
                    <el-tag
                      @close="deleteRights(scope.row, item2.id)"
                      closable
                      type="success"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级 -->
                  <el-col :span="18">
                    <el-tag
                      closable
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      @close="deleteRights(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{ scope.row }}</pre> -->
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <!-- 使用作用域插槽渲染功能按钮 -->
        <el-table-column label="操作" width="400px">
          <template v-slot="scope">
            <!-- 编辑按钮 -->
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row)"
              >编辑</el-button
            >
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="showDeleteMessageBox(scope.row)"
              >删除</el-button
            >
            <!-- 分配权限按钮 -->
            <el-button
              @click="showSetRightDialog(scope.row)"
              type="warning"
              size="mini"
              icon="el-icon-setting"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色的dialog -->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%">
      <el-form
        :model="addUserInfo"
        :rules="addUserInfoRules"
        ref="addUserInfoRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addUserInfo.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addUserInfo.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelAddUser">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色的dialog -->
    <el-dialog title="编辑角色" :visible.sync="editDialogVisible" width="50%">
      <el-form
        :model="editUserInfo"
        :rules="addUserInfoRules"
        ref="editUserInfoRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editUserInfo.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editUserInfo.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelEditUser">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色权限的dialog -->
    <el-dialog
      title="分配角色权限"
      :visible.sync="setDialogVisible"
      width="50%"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="rightsList"
        :props="rightsProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setUserRight">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色权限列表
      rolesList: [],
      // 权限数据
      rightsList: [],
      // 树形组件props
      rightsProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认勾选已有的权限
      defKeys: [],
      // 选中节点和半选中节点
      // checkedKey: [],
      // halfCheckedKey: [],
      // 控制添加角色dialog显示
      addDialogVisible: false,
      editDialogVisible: false,
      setDialogVisible: false,
      roleId: '',
      // 添加角色的信息
      addUserInfo: {
        roleName: '',
        roleDesc: ''
      },
      // 修改角色信息
      editUserInfo: {
        roleName: '',
        roleDesc: '',
        id: ''
      },
      // 添加角色的规则
      addUserInfoRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: false, message: '请输入角色描述', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 获取角色权限列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('res.meta.msg')
      console.log(res)
      this.rolesList = res.data
    },
    // 添加角色
    async addUser() {
      const { data: res } = await this.$http.post('roles', this.addUserInfo)
      if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
      this.addDialogVisible = !this.addDialogVisible
      this.$message.success(res.meta.msg)
      this.$refs.addUserInfoRef.resetFields()
      this.getRolesList()
    },
    // 取消添加
    cancelAddUser() {
      this.$refs.addUserInfoRef.resetFields()
      this.addDialogVisible = !this.addDialogVisible
    },
    // 弹出编辑角色dialog
    showEditDialog(userInfo) {
      this.editUserInfo = userInfo
      this.editDialogVisible = !this.editDialogVisible
    },
    // 编辑角色
    async editUser() {
      const { data: res } = await this.$http.put(
        'roles/' + this.editUserInfo.id,
        {
          roleName: this.editUserInfo.roleName,
          roleDesc: this.editUserInfo.roleDesc
        }
      )
      if (res.meta.status !== 200) return this.$message.msg(res.meta.msg)
      this.editDialogVisible = !this.editDialogVisible
      this.$message.success('修改角色成功')
    },
    // 取消修改
    cancelEditUser() {
      this.$refs.editUserInfoRef.resetFields()
      this.editDialogVisible = !this.editDialogVisible
    },
    // 删除角色
    async showDeleteMessageBox(userInfo) {
      const confirmRes = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (confirmRes !== 'confirm') return this.$message.info('取消删除')
      const { data: res } = await this.$http.delete('roles/' + userInfo.id)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getRolesList()
    },
    // 删除角色权限
    async deleteRights(role, rightId) {
      const confirmRes = await this.$confirm(
        '此操作将删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (confirmRes !== 'confirm') return this.$message.info('取消删除')
      // console.log(rolesId.id, rightsId)
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      role.children = res.data
      return this.$message.success(res.meta.msg)
    },
    // 展示分配权限的dialog,并且获取数据
    async showSetRightDialog(role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rightsList = res.data
      // 在递归前清空数组，防止显示其他权限的BUG
      this.defKeys = []
      // 递归
      this.getDefKeys(role, this.defKeys)
      this.setDialogVisible = !this.setDialogVisible
    },
    // 分配权限
    async setUserRight() {
      const keysArr = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // 这里要注意，权限列表是列表，而不是数组
      const idStr = keysArr.join(',')
      console.log(idStr)
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        {
          rids: idStr
        }
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.getRolesList()
      this.setDialogVisible = !this.setDialogVisible
      return this.$message.success(res.meta.msg)
    },
    // 递归获取角色三级权限id
    getDefKeys(data, arr) {
      if (!data.children) {
        return arr.push(data.id)
      }
      data.children.map((item) => {
        this.getDefKeys(item, arr)
      })
    }
  },
  created() {
    this.getRolesList()
  }
}
</script>

<style lang="less" scoped>
.bt {
  border-top: 1px solid #eee;
}
.bb {
  border-bottom: 1px solid #eee;
}
.el-tag {
  margin: 7px;
}
.el-row {
  display: flex;
  align-items: center;
}
</style>
